<template>
  <div class="health-page">
    <h2>健康状况</h2>
    <el-button type="warning" @click="updateData()" style="margin-left: 32px;margin-top: 5px;margin-bottom: 20px">没有设备？点击手动输入数据</el-button>
    <el-row :gutter="10" style="margin-left: 30px">
      <el-col :span="4">
        <el-card class="health-card" style="padding-bottom: 32px">
          <h4>身高</h4>
          <p class="value">{{ healthData.height }} cm</p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="health-card">
          <h4>体重</h4>
          <p class="value">{{ healthData.weight }} kg</p>
          <p class="status">{{ getWeightStatus(healthData.weight, healthData.height) }}</p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="health-card">
          <h4>体脂率</h4>
          <p class="value">{{ (healthData.BFP * 100).toFixed(2) }}%</p>
          <p class="status">{{ getBFPStatus(healthData.BFP) }}</p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="health-card">
          <h4>骨量</h4>
          <p class="value">{{ healthData.BM }} kg</p>
          <p class="status">{{ getBMStatus(healthData.BM) }}</p>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="health-card">
          <h4>肌肉量</h4>
          <p class="value">{{ healthData.MM }} kg</p>
          <p class="status">{{ getMMStatus(healthData.MM) }}</p>
        </el-card>
      </el-col>
    </el-row>

    <el-main>
      <el-card>
        <h4>个人饮食健康分析</h4>
        <el-button type="primary" @click="analyzeWithDeepSeek" style="margin-bottom: 10px;" :disabled="isButtonDisabled">开始分析</el-button>
        <div class="analysis-result" v-if="analysisResult" v-html="parsedAnalysisResult"></div>
      </el-card>
    </el-main>

    <!-- 弹窗表单 -->
    <el-dialog v-model="dialogVisible" title="手动输入健康数据" width="30%">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="身高 (cm)">
          <el-input v-model="formData.height" type="number" />
        </el-form-item>
        <el-form-item label="体重 (kg)">
          <el-input v-model="formData.weight" type="number" />
        </el-form-item>
        <el-form-item label="体脂率 (0.**)">
          <el-input v-model="formData.BFP" type="number" />
        </el-form-item>
        <el-form-item label="骨量 (kg)">
          <el-input v-model="formData.BM" type="number" />
        </el-form-item>
        <el-form-item label="肌肉量 (kg)">
          <el-input v-model="formData.MM" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitData">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { marked } from 'marked';
import { ElMessage, ElLoading } from 'element-plus';

// 用户健康数据
const healthData = ref({
  height: 0,
  weight: 0,
  BFP: 0,
  BM: 0,
  MM: 0
});

// 弹窗是否可见
const dialogVisible = ref(false);

// 表单数据
const formData = ref({
  height: 0,
  weight: 0,
  BFP: 0,
  BM: 0,
  MM: 0
});

// 打开弹窗
const updateData = () => {
  formData.value = { ...healthData.value };
  dialogVisible.value = true;
};

// 提交数据
const submitData = async () => {
  try {
    const uid = localStorage.getItem('uid');
    if (!uid) {
      ElMessage.error('请先登录');
      return;
    }

    // 更新本地数据
    healthData.value = { ...formData.value };

    // 发送到后端插入
    await axios.post('http://localhost:8080/v1/user/health/insert', {
      uid: uid,
      height: formData.value.height,
      weight: formData.value.weight,
      bfp: formData.value.BFP,
      bm: formData.value.BM,
      mm: formData.value.MM,
    });

    ElMessage.success('数据插入成功');
    dialogVisible.value = false;
  } catch (error) {
    console.error('数据插入失败:', error);
    ElMessage.error('数据插入失败，请稍后重试');
  }
}

// 判断按钮是否禁用
const isButtonDisabled = computed(() => {
  return !(healthData.value.height != 0 && healthData.value.weight != 0);
});

// 分析结果
const analysisResult = ref('');

// 解析后的分析结果
const parsedAnalysisResult = computed(() => {
  return marked.parse(analysisResult.value);
});

// 获取健康数据
const fetchHealthData = async () => {
  try {
    const uid = localStorage.getItem('uid');
    if (!uid) {
      ElMessage.error('请先登录');
      return;
    }

    const response = await axios.get(`http://localhost:8080/v1/user/health/data/${uid}`);
    console.log('Response Data:', response.data);

    const data = response.data.data;
    healthData.value = {
      height: data.height || 0,
      weight: data.weight || 0,
      BFP: data.bfp || 0,
      BM: data.bm || 0,
      MM: data.mm || 0
    };

    console.log('Updated Health Data:', healthData.value); // 添加日志
  } catch (error) {
    console.error('获取健康数据失败:', error);
    ElMessage.error('获取健康数据失败，请稍后重试');
  }
};


onMounted(() => {
  fetchHealthData();
});

// 判断体重状态（基于 BMI）
const getWeightStatus = (weight, height) => {
  if (height === 0) return '未知';
  const bmi = (weight / ((height / 100) ** 2)).toFixed(2);
  if (bmi < 18.5) return '偏瘦';
  if (bmi >= 18.5 && bmi < 24) return '正常';
  if (bmi >= 24 && bmi < 28) return '超重';
  return '肥胖';
};

// 判断体脂率状态
const getBFPStatus = (bfp) => {
  const bfpPercentage = bfp * 100;
  if (bfpPercentage < 15) return '偏低';
  if (bfpPercentage >= 15 && bfpPercentage < 25) return '正常';
  return '偏高';
};

// 判断骨量状态
const getBMStatus = (bm) => {
  if (bm < 2.5) return '偏低';
  if (bm >= 2.5 && bm < 3.5) return '正常';
  return '偏高';
};

// 判断肌肉量状态
const getMMStatus = (mm) => {
  if (mm < 30) return '偏低';
  if (mm >= 30 && mm < 40) return '正常';
  return '偏高';
};

// 调用 DeepSeek AI 进行分析
async function analyzeWithDeepSeek() {
  const loading = ElLoading.service({
    lock: true,
    text: '已开始生成一周食谱，请稍候',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  // 清空之前的结果
  analysisResult.value = '';

  try {
    const { height, weight, BFP, BM, MM } = healthData.value;
    const bmi = (weight / ((height / 100) ** 2)).toFixed(2);

    const response = await fetch('http://localhost:8080/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream'
      },
      body: JSON.stringify({
        prompt: `你是一个专业的健康分析师，请根据以下数据评估用户的健康状况：
- 体脂率（BFP）: ${BFP * 100}%
- 骨量（BM）: ${BM} kg
- 肌肉量（MM）: ${MM} kg
- BMI: ${bmi}

若BMI、体脂率、骨量和肌肉量有为0的，则根据有数据的那几项分析。
根据用户健康数据生成一周健身食谱建议（要求包含每天三餐）
要求：给出专业、详细的饮食计划，适合健身目标，使用中文，纯文本输出，不要用制表符，使用一种字体;`
      })
    });

    if (!response.ok || !response.body) throw new Error('网络响应异常');

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';
    let jsonBuffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });

      // 按SSE协议分割事件
      const events = buffer.split('\n\n');
      buffer = events.pop() || '';

      for (const event of events) {
        const lines = event.split('\n').filter(l => l.startsWith('data:'));

        for (const line of lines) {
          jsonBuffer += line.slice(5).trim();

          try {
            const json = JSON.parse(jsonBuffer);
            jsonBuffer = '';

            if (json.choices?.[0]?.delta?.content) {
              analysisResult.value += json.choices[0].delta.content;
            }
          } catch {
            // 等待完整JSON数据
          }
        }
      }
    }
  } catch (error) {
    console.error('分析失败:', error);
    analysisResult.value = '分析服务暂时不可用，请稍后再试';
    ElMessage.error('分析请求失败');
  } finally {
    loading.close();
  }
}
</script>

<style scoped>
.health-page {
  padding: 20px;
  color: #333;
}

.health-card {
  text-align: center;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.health-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
}

.value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 8px 0;
}

.status {
  font-size: 12px;
  color: #666;
}

.analysis-result {
  white-space: pre-wrap;
  line-height: 1.6;
  font-size: 16px;
  color: #333;

  h1, h2, h3, h4, h5, h6 {
    margin: 20px 0 10px;
    font-weight: bold;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
  }

  th, td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
  }

  th {
    background-color: #f2f2f2;
  }

  ul, ol {
    padding-left: 20px;
  }

  p {
    margin: 10px 0;
  }
}
</style>
